import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/supplier/api/api_supplier.dart';
import 'package:tender_flutter/page/supplier/model/certificate_entity.dart';
import 'package:tender_flutter/page/supplier/model/supplier_detail_entity.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/net_image.dart';
import 'package:url_launcher/url_launcher.dart';

class SupplierDetailPage extends StatefulWidget {
  final int supplierId;

  const SupplierDetailPage({Key key, this.supplierId}) : super(key: key);

  @override
  _SupplierDetailPageState createState() => _SupplierDetailPageState();
}

class _SupplierDetailPageState extends State<SupplierDetailPage> {
  SupplierDetailEntity _detailEntity;
  SupplierContactEntity _contactEntity;

  LoadState _loadState = LoadState.State_Loading;

  /// 获取供应商联系方式
  Future<SupplierContactEntity> _getContact() async {
    if (_contactEntity != null) {
      return _contactEntity;
    }
    ToastUtils.showLoading("");
    var response = await ApiSupplier.getSupplierContact<SupplierContactEntity>(
        widget.supplierId);
    ToastUtils.dismissLoading();
    _contactEntity = response.result;
    return _contactEntity;
  }

  /// 获取详情
  Future<ApiResponse<SupplierDetailEntity>> _getDetail() async {
    return await ApiSupplier.getSupplierDetail<SupplierDetailEntity>(
        widget.supplierId);
  }

  FutureBuilder<ApiResponse<SupplierDetailEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _getDetail(),
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<SupplierDetailEntity>> snapshot) {
          if (snapshot.hasData) {
            _detailEntity = snapshot.data.result;
            _loadState = LoadState.State_Success;
            return LoadStateLayout(
              bgColor: ThemeColors.colorWhite,
              state: _loadState,
              successWidget: _initBody(),
            );
          } else {
            return LoadStateLayout(
              bgColor: ThemeColors.colorWhite,
              state: _loadState,
            );
          }
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ThemeColors.colorWhite,
        appBar: _initAppBar(),
        body: _buildFutureBuilder());
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(context, Text("供应商详情", style: FonStyle.navTextStyle()));
  }

  /// 个人供应商
  Widget _initBody() {
    return Column(children: [
      Expanded(
          child: Container(
              child: SingleChildScrollView(
        padding: EdgeInsets.all(ScreenAdapter.width(30)),
        physics: BouncingScrollPhysics(),
        child: Column(
          children: _getBodyWidget(),
        ),
      ))),
      _initBottomLayout()
    ]);
  }

  List<Widget> _getBodyWidget() {
    if (int.parse(_detailEntity.type) == AppConstant.SUPPLIER_BUSINESS) {
      /// 企业供应商
      return [
        _initTitleView(),
        SizedBox(height: ScreenAdapter.height(15)),
        Divider(color: ThemeColors.colorType49),
        SizedBox(height: ScreenAdapter.height(15)),
        _initInfoItem("联系人", _detailEntity.contact ?? "-"),
        SizedBox(height: ScreenAdapter.height(40)),
        _initInfoItem(
            "详细地址", !isEmpty(_detailEntity.area) ? _detailEntity.area : "暂无"),
        SizedBox(height: ScreenAdapter.height(40)),
        _initMultipleInfoItem("主营项目",
            !isEmpty(_detailEntity.remark) ? _detailEntity.remark : "暂无"),
        SizedBox(height: ScreenAdapter.height(40)),
        _initInfoItem("拥有资质", ""),
        // SizedBox(height: ScreenAdapter.height(40)),
        _initCertificatListView()
      ];
    } else {
      /// 个人供应商
      return [
        _initTitleView(),
        SizedBox(height: ScreenAdapter.height(15)),
        Divider(color: ThemeColors.colorType49),
        SizedBox(height: ScreenAdapter.height(15)),
        _initInfoItem(
            "详细地址", !isEmpty(_detailEntity.area) ? _detailEntity.area : "暂无"),
        SizedBox(height: ScreenAdapter.height(40)),
        _initInfoItem(
            "所在企业",
            !isEmpty(_detailEntity.companyName)
                ? _detailEntity.companyName
                : "暂无"),
        SizedBox(height: ScreenAdapter.height(40)),
        _initInfoItem("资质证书", ""),
        // SizedBox(height: ScreenAdapter.height(40)),
        _initCertificatListView()
      ];
    }
  }

  /// 头部信息
  Widget _initTitleView() {
    return Row(
      children: <Widget>[
        _getImageView(),
        Expanded(
            child: Column(
          // mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              _detailEntity.title ?? "-",
              maxLines: 2,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(36),
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(height: ScreenAdapter.height(25)),
            Row(
              // mainAxisAlignment: MainAxisAlignment.spaceBetween,
              // mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(
                      left: ScreenAdapter.width(15),
                      right: ScreenAdapter.width(15),
                      top: ScreenAdapter.width(6),
                      bottom: ScreenAdapter.width(6)),
                  child: Text(_detailEntity.area ?? "-",
                      style: TextStyle(
                          color: ThemeColors.colorType40,
                          fontSize: ScreenAdapter.sp(24))),
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType20,
                      borderRadius: new BorderRadius.circular(3)),
                ),
                SizedBox(width: ScreenAdapter.width(15)),
                Container(
                  padding: EdgeInsets.only(
                      left: ScreenAdapter.width(15),
                      right: ScreenAdapter.width(15),
                      top: ScreenAdapter.width(6),
                      bottom: ScreenAdapter.width(6)),
                  child: Text(_detailEntity.labels ?? "-",
                      style: TextStyle(
                          color: ThemeColors.colorType42,
                          fontSize: ScreenAdapter.sp(24))),
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType41,
                      borderRadius: new BorderRadius.circular(3)),
                ),
              ],
            )
          ],
        ))
      ],
    );
  }

  /// 获取头像
  Widget _getImageView() {
    if (int.parse(_detailEntity.type) == AppConstant.SUPPLIER_PERSION) {
      /// 个人
      return Container(
        width: ScreenAdapter.width(132),
        height: ScreenAdapter.width(132),
        margin: EdgeInsets.only(right: ScreenAdapter.width(18)),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: Text(
            !isEmpty(_detailEntity.title)
                ? _detailEntity.title.substring(0, 1)
                : "人",
            style: TextStyle(
                color: ThemeColors.colorWhite,
                fontSize: ScreenAdapter.sp(60),
                fontWeight: FontWeight.bold)),
      );
    } else {
      /// 企业供应商
      bool isPortrait = _detailEntity.companyLogo != null &&
          _detailEntity.companyLogo.isNotEmpty;
      return Container(
        width: ScreenAdapter.width(132),
        height: ScreenAdapter.width(132),
        margin: EdgeInsets.only(right: ScreenAdapter.width(18)),
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: isPortrait ? ThemeColors.colorWhite : ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: isPortrait
            ? MyNetImage(
                url: _detailEntity.companyLogo ?? "",
                radius: BorderRadius.circular(ScreenAdapter.width(14)))
            : Text("企",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(60),
                    fontWeight: FontWeight.bold)),
      );
    }
  }

  Widget _initInfoItem(String title, String content, {Color bgColor}) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
            margin: EdgeInsets.only(
                top: ScreenAdapter.height(8), right: ScreenAdapter.width(10)),
            height: ScreenAdapter.height(20),
            width: ScreenAdapter.width(4),
            color: ThemeColors.colorType6),
        Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[
          Text(title,
              style: TextStyle(
                  color: ThemeColors.colorType1,
                  fontSize: ScreenAdapter.sp(30),
                  fontWeight: FontWeight.bold)),
          SizedBox(height: ScreenAdapter.height(10)),
          Offstage(
              offstage: content.isEmpty ? true : false,
              child: Text(content,
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(30))))
        ])
      ],
    );
  }

  Widget _initMultipleInfoItem(String title, String content) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Container(
            margin: EdgeInsets.only(
                top: ScreenAdapter.height(10), right: ScreenAdapter.width(10)),
            height: ScreenAdapter.height(20),
            width: ScreenAdapter.width(4),
            color: ThemeColors.colorType6),
        Expanded(
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
              Text(title,
                  style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(30),
                      fontWeight: FontWeight.bold)),
              SizedBox(height: ScreenAdapter.height(20)),
              Container(
                  width: double.infinity,
                  padding: EdgeInsets.all(ScreenAdapter.width(20)),
                  decoration: BoxDecoration(
                      color: ThemeColors.colorType11,
                      borderRadius:
                          BorderRadius.circular(ScreenAdapter.width(14))),
                  child: Text(content,
                      style: TextStyle(
                          color: ThemeColors.colorType1,
                          fontSize: ScreenAdapter.sp(30)))),
            ]))
      ],
    );
  }

  /// 资质列表
  Widget _initCertificatListView() {
    List<Map<String, String>> cerDatas = [];
    for (CertificateEntity entity in _detailEntity.profiles) {
      cerDatas.add({
        "资质编号": entity.code ?? "",
        "发证机关": entity.issueAuthority ?? "",
        "发证日期": entity.issueDate ?? "",
        "截止日期": entity.endDate ?? "",
        "资质类别": entity.qualificationType ?? ""
      });
    }
    return ListView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: cerDatas.length,
        itemBuilder: (context, index) {
          return _getCertificateItem(context, index, cerDatas[index]);
        });
  }

  /// 底部按钮试图
  Widget _initBottomLayout() {
    return Container(
        height: ScreenAdapter.height(100),
        child: Row(children: [
          Expanded(
              child: FlatButton(
                  onPressed: () {
                    _getContact().then((value) {
                      if (value != null) {
                        Clipboard.setData(new ClipboardData(text: value.wx));
                        ToastUtils.show("复制成功");
                        Future.delayed(Duration(milliseconds: 400), () async {
                          String url = "weixin://";
                          if (await canLaunch(url)) {
                            await launch(url);
                          } else {
                            throw 'Could not launch $url';
                          }
                        });
                      } else {
                        ToastUtils.show("微信账号异常");
                      }
                    });
                  },
                  height: double.infinity,
                  color: ThemeColors.colorType42,
                  shape: RoundedRectangleBorder(),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(RPath.imgPath + "icon_wecha_white.png",
                          fit: BoxFit.contain,
                          width: ScreenAdapter.width(44),
                          height: ScreenAdapter.width(44)),
                      Text("  微信联系",
                          style: TextStyle(
                              fontSize: ScreenAdapter.sp(30),
                              color: ThemeColors.colorWhite))
                    ],
                  ))),
          Expanded(
              child: FlatButton(
                  onPressed: () {
                    _getContact().then((value) => {
                          if (value != null)
                            {launch("tel:" + value.phone ?? "")}
                        });
                  },
                  height: double.infinity,
                  color: ThemeColors.colorType6,
                  shape: RoundedRectangleBorder(),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(RPath.imgPath + "icon_tel_white.png",
                          fit: BoxFit.contain,
                          width: ScreenAdapter.width(35),
                          height: ScreenAdapter.width(35)),
                      Text("  拨打电话",
                          style: TextStyle(
                              fontSize: ScreenAdapter.sp(30),
                              color: ThemeColors.colorWhite))
                    ],
                  )))
        ]));
  }

  /// 资质表格Item
  Widget _getCertificateItem(
      BuildContext context, int index, Map<String, String> datas) {
    return Container(
        margin: EdgeInsets.symmetric(vertical: ScreenAdapter.height(15)),
        child: Table(
          //所有列宽
          columnWidths: const {
            //列宽
            0: FixedColumnWidth(100.0),
            1: FixedColumnWidth(200.0),
          },
          //表格边框样式
          border: TableBorder.all(
            width: 1.0,
            color: ThemeColors.colorType47,
            style: BorderStyle.solid,
          ),
          children: datas.keys.map((e) => _getCCell(e, datas[e])).toList(),
        ));
  }

  TableRow _getCCell(String title, String content) {
    return TableRow(children: [
      Container(
        height: ScreenAdapter.height(70),
        alignment: Alignment.center,
        child: Text(
          title,
          style: TextStyle(
            color: ThemeColors.colorType24,
            fontSize: ScreenAdapter.sp(30),
          ),
        ),
      ),
      Container(
        height: ScreenAdapter.height(70),
        alignment: Alignment.center,
        child: Text(
          content,
          style: TextStyle(
            color: ThemeColors.colorType7,
            fontSize: ScreenAdapter.sp(30),
          ),
        ),
      ),
    ]);
  }
}
